package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
调用与当前类Test5所在同一个包中被标注@AutoRunClass标注的类中那些被注解@AutoRunMethod的方法
 */
public class Test5 {
    public static void main(String[] args) throws Exception {
        File dir = new File(
                Test5.class.getResource(".").toURI()
        );
        String packagename = Test5.class.getPackage().getName();
        File[] subs = dir.listFiles(f -> f.getName().endsWith(".class"));
        for(File sub : subs) {
            String filename = sub.getName();
            String classname= filename.substring(0, filename.indexOf("."));
            Class cls = Class.forName(packagename + "." + classname);
            if(cls.isAnnotationPresent(AutoRunClass.class)) {
                Object obj = cls.newInstance();
                Method[] methods =cls.getDeclaredMethods();
                for(Method method : methods) {
                    if(method.isAnnotationPresent(AutoRunMethod.class)) {
                        method.invoke(obj);
                    }
                }
            }
        }
    }
}
